<?php

namespace app\admin\model;

use think\Db;
use think\Exception;
use think\Model;

/**
 * 审批申请表
 */
class AppForm extends Common
{
    //

    protected $autoWriteTimestamp = true;
    protected $createTime = "create_time";
    protected $updateTime = "update_time";

    /**
     * 提交表单
     * @var int
     */
    public static $STATUS_SUBMIT_FORM = 1;
    /**
     * 等待审核
     * @var int
     */
    public static $STATUS_AUDTI_WAITING = 2;
    /**
     * 审核通过
     * @var int
     */
    public static $STATUS_AUDIT_PASS = 3;
    /**
     * 审核拒绝
     * @var int
     */
    public static $STATUS_AUDIT_REJECT = 4;
    /**
     * 已用章未上传图片
     * @var int
     */
    public static $STATUS_USED = 5;
    /**
     * 审核排队等待中
     * @var int
     */
    public static $STATUS_FINISHED = 6;

    public function getStatusTxtAttr($value, $data)
    {
        $configModel = new Config();
        $statuesCache = $configModel->getSealAppFormStatues($data['status']);
        return $statuesCache['name'];
    }

    public function getUnFinishedAttr()
    {
        return $this->unFinished();
    }


    /**
     * 审核申请
     * <p>审核成功则返回true，否则抛出异常</p>
     * @param User $auditor {@link User} 审核人
     * @return false|void
     */
    public function audit()
    {
        $form_id=$this->id;
        $uid = session('id');
        $mid=db('approval_process')->where(['form_id'=>$form_id,'uid'=>$uid])->order('id desc')->value('id');

            //同意 同意的话还要看后面的有没有人，审批流程有没有结束
            
            
            db('approval_process')->where(['id'=>$mid])->update(['status'=>2,'app_time'=>time()]);

            $id_list=db('approval_process')->where(['form_id'=>$form_id])->order('id asc')->field('id')->select();
            
            $max_ids=max($id_list);
            $max_id=$max_ids['id'];
            $ids = array_column($id_list,'id');
            //当前ID的下标值
            $key = array_search($mid, $ids);
            
            //看最大值大于$id不，大于就代表后面还有审批人
            if($max_id>$mid){
                // $next_id=$mid+1;
                $next_id=$id_list[$key+1]['id'];

                //轮到下一个人审核 status:1为当前审核人
                db('approval_process')->where(['id'=>$next_id])->update(['status'=>1]);
                
                
                
                                //openid:审核人的app_openid   $uid 申请人的uid  $res  表单ID
                $sh_uid=db('approval_process')->where(['id'=>$next_id])->value('uid');
                $openid=db('user')->where(['id'=>$sh_uid])->value('app_openid');

                $form_id=db('approval_process')->where(['id'=>$next_id])->value('form_id');
                $sq_uid=db('app_form')->where(['id'=>$form_id])->value('uid');
                //$this->send_subscribe($openid,$sq_uid,$form_id);
            }else{
                //审批流程走完了
                db('approval_process')->where(['form_id'=>$form_id])->update(['form_state'=>1]);
                db('app_form')->where(['id'=>$form_id])->update(['status'=>4]);

                //走完了，要发送通知给申请人
                //openid:申请人的app_openid   $uid 申请人的uid  $res  表单ID
                $uid=db('app_form')->where(['id'=>$form_id])->value('uid');
                $openid=db('user')->where(['id'=>$uid])->value('app_openid');
                //$this->send_subscribe31($openid,$uid,$form_id);
            }
    }

    /**
     * 审核流程拒绝
     * @param User $auditor 当前审核人 {@link User}
     * @param String $reson 拒绝原因
     * @return bool
     * @throws Exception
     */
    public function reject(User $auditor, $reson)
    {
		
            $form_id=$this->id;
            $uid = session('id');
            $mid=db('approval_process')->where(['form_id'=>$form_id,'uid'=>$uid])->order('id desc')->value('id');
            //要写拒绝原因
            $remark_content=$reson;
            if(!$remark_content){
                $remark_content='';
            }
            // if(!$remark){
            //     apiReturn(2,'拒绝原因不能为空');
            // }
            db('app_form')->where(['id'=>$form_id])->update(['status'=>3]);
            db('approval_process')->where(['id'=>$mid])->update(['status'=>3,'remark'=>4,'remark_content'=>$remark_content,'app_time'=>time()]);

    }

    /**
     * 获取申请统计
     * @param $companyId
     * @return mixed
     */
    public function getApplyStatistics($companyId, $where = null)
    {
        return $this->with(['seal'])->field(['seal_id, count(*) as formCount, sum(use_count) as usedCount'])
            ->where('company_id', $companyId)
            ->where($where)
            ->where('status', 'in', [AppForm::$STATUS_SUBMIT_FORM, AppForm::$STATUS_AUDTI_WAITING, AppForm::$STATUS_AUDIT_PASS, AppForm::$STATUS_AUDIT_REJECT])
            ->group("seal_id");
    }

    /**
     *
     * 是否用章完成
     * @return bool
     */
    public function unFinished()
    {
        $unFinishedStatus = [1, 3];
        return in_array($this->status, $unFinishedStatus);
    }

    /**
     * 未使用申请预定义查询
     * @param $query
     */
    protected function scopeAuditing($query)
    {
        $query->where('status', 'in', [AppForm::$STATUS_SUBMIT_FORM, AppForm::$STATUS_AUDTI_WAITING, AppForm::$STATUS_AUDIT_PASS, AppForm::$STATUS_AUDIT_REJECT]);
    }

    /**
     * 企业预定义查询
     * <p>例如：要查询ID为1的企业的印章申请，(new AppForm())->company(1)->select()</p>
     * @param $query
     * @param $companyId
     */
    protected function scopeCompany($query, $companyId)
    {
        $query->where('company_id', $companyId);
    }

    /**
     * 获取有效的审核流程
     */
    public function effectiveProcessFlow()
    {
        return $this->hasMany('ApprovalProcess', 'form_id')->where("status", 'in', [ApprovalProcess::$AUDIT_WAITING, ApprovalProcess::$AUDIT_QUEUE_WAIT])->where("is_obsolete", 1);
    }

    /**
     * 将审核流程进行分组排序
     * @return array|bool
     */
    public function processFlowGroup()
    {
        return processToGroupSort($this->processFlowGroup);
    }

    /**
     * 获取最后一个审核流程
     * @return array|bool|\PDOStatement|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getLastAuditFlow()
    {
        return $this->processFlows()->order('id desc')->find();
    }

    /**
     * 获取下一个审批流程
     * @param $auditFlow
     * @return array|bool|\PDOStatement|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getNextAuditFlow($auditFlow)
    {
        return $this->processFlows()->where('id', '>', $auditFlow)->order('id', 'asc')->find();
    }

    /**
     * 获取当前审核人
     * @return \think\model\relation\HasOne
     */
    public function getCurrentAuditFLow()
    {
        return $this->hasOne('ApprovalProcess', 'form_id')->with(['user'])->where('status', 1);
    }

    /**
     * 附件关联
     * @return \app\extra\HasManyJoin
     */
    public function attachments()
    {
        return $this->hasManyJoin('Picture', 'id', 'imgs');
    }

    /**
     * 用章流程
     * @return \app\extra\HasManyJoin
     */
    public function processFlows()
    {
        return $this->hasManyJoin('ApprovalProcess', 'form_id');
    }

    /**
     * 用户关联
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('User', 'uid');
    }

    /**
     * 印章关联
     * @return \think\model\relation\BelongsTo
     */
    public function seal()
    {
        return $this->belongsTo('Seal', 'seal_id');
    }

    /**
     * 审核类型关联
     * @return \think\model\relation\BelongsTo
     */
    public function approval()
    {
        return $this->belongsTo('Approval', 'app_id');
    }

}
